<template>
    <div class="home">
        <div>
            <div class="shoppingCar">
                <div class="topTiele">
                    <span style="color: #FF6600;cursor: pointer" @click="changeDesc">整单打包/备注</span>
                    <span style="cursor: pointer" @click="clearData"><i class="el-icon-delete"></i>清空</span>
                </div>
                <div class="menuListBox">
                    <div v-if="shoppingCar.length == 0">
                        <el-empty :image-size="50" description="暂无订单"></el-empty>
                    </div>
                    <div v-else>
                        <div class="menu-item" v-for="(item, index) in shoppingCar" :key="index">
                            <div class="item-details">
                                <p class="item-name">{{ item.name }}</p>
                                <p class="item-desc">{{ item.notes }}</p>
                            </div>
                            <div class="item-price-counter">
                                <span class="item-price">¥ {{ item.price }}</span>
                                <div class="custom-input-number">

                                    <div class="custom-counter">
                                        <button class="counter-btn minus" @click="decrease(item.num, index)">
                                            <span>-</span>
                                        </button>
                                        <span class="item-quantity">{{ item.num }}</span>
                                        <button class="counter-btn plus" @click="increase(item.num, index)">+</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="settlement">
                <div class="settlementBox">
                    <div class="settlementLeft">
                        <p class="settlement_price"><span>合计：</span><span
                                style="color: #FF6600;font-size:16px;font-weight: 600">￥{{ total }}</span>
                        </p>
                        <p class="settlementTips">
                            <span v-for="item in desc" :key="item">{{ item.desc }}</span>

                        </p>
                    </div>
                    <el-button @click="submitOrder"> 提交订单</el-button>
                </div>
            </div>
        </div>

        <div class="main_MenuList">
            <div style="width: 100%">
                <div class="firstMenu">
                    <p :class="pid == item.id ? 'pON' : ''" @click="chanFirstMenu(item.id, item.child)" :key="item.id"
                       v-for="item in menu_cateList">{{ item.title }}</p>
                </div>
                <div class="secondMenu">
                    <p @click="cid = children.id; queryKiosk_menu_list()" :class="cid == children.id ? 'pON' : ''"
                       :key="children.id" v-for="children in secondMenuList">
                        {{ children.title }}</p>
                </div>
            </div>
            <div class="zxf_menu_list" v-if="kiosk_menu_list.length !== 0">
                <div @click="changeParameter(item)" :key="index" v-for="(item, index) in kiosk_menu_list"
                     style="margin-right: 10px;width: 190px;height: 130px;border-radius: 10px;background: white;margin-bottom: 10px">
                    <img :src="item.image" style="width: 190px;height: 90px ;border-radius: 10px 10px 0 0 ;" />
                    <p style="text-align: center;background: white;height: 30px;line-height: 30px;border-radius: 10px;">
                        {{ item.name }}
                    </p>
                </div>
            </div>
            <div v-else>
                <el-empty :image-size="50" description="暂无菜单数据"></el-empty>
            </div>
        </div>
        <el-dialog ref="dialogContent" title="规格选取" :visible.sync="isShowDialog" :close-on-click-modal="false" width="520px">
            <div ref="dialogContent">
                <div class="parameterBox">
                    <h3>规格：</h3>
                    <div>
                        <div @click="detailData.specs_price = item.size; detailData.price = item.price; $forceUpdate()" v-for="item in parameter.sale_price" :key="item.id">
                            <el-button type="info" plain style="margin-right: 10px;" :class="detailData.specs_price == item.size ? 'divOn' : ''">{{ item.size }} | {{ item.price }}</el-button>
                        </div>
                    </div>
                </div>
                <div class="parameterBox1" v-if="parameter.is_setmeal==2">
                    <h3>所含菜品:</h3>
                    <div>
                        <div v-for="(item,index) in parameter.menu" :key="index">
                            <span style="margin-right: 10px;font-size: 14px">{{index+1}}.{{item.name}}</span>
                        </div>
                    </div>
                </div>

                <div v-for="(child, index) in parameter.specs" :key="index">
                    <div class="parameterBox1">
                        <h3>{{ child.title }}：</h3>
                        <div>
                            <div @click="addNote(childs, child.price)" v-for="childs in child.price" :key="childs">
                                <el-button type="info" plain style="margin-right: 10px;" :class="notes.includes(childs) ? 'divOn' : ''">{{ childs }}</el-button>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <div style="text-align: right;margin-top: 1vw;margin-right: 1vw">
                <el-button type="info" @click="isShowDialog = false">取消</el-button>
                <el-button type="primary" :loading="subloading" @click="submitData()">确定</el-button>
            </div>
        </el-dialog>
        <!--备注选择-->
        <el-dialog title="备注选择" :visible.sync="isShowDialog1" :close-on-click-modal="false" width="520px">
            <div class="descBox">
                <h3>备注：</h3>
                <div>
                    <div @click="addDesc(item.desc)" :class="desc.indexOf(item.desc) !== -1 ? 'divOn' : ''"
                         v-for="item in remarkList" :key="item.desc">
                        <span>{{ item.desc }}</span>
                    </div>
                </div>
            </div>
            <div style="text-align: right;margin-top: 1vw;margin-right: 1vw">
                <el-button class="common_btn-white" @click="isShowDialog1 = false">取消</el-button>
                <el-button class="common_btn-defalut" type="primary" @click="isShowDialog1 = false">确定</el-button>
            </div>
        </el-dialog>
    </div>

</template>

<script>
import UploadImg from '@/components/upload-img'
import { menu_cateList, menu_list, create_order, remarks_list,setmealList } from '@/services/model/orderList'
import constUrl from '@/services/env'
import { getLocalStorageItem } from '@/utils/storage-helper'
import {getLodop} from "@/utils/Lodop";

export default {
    components: { UploadImg, },
    data() {
        return {
            remarkList: [],
            seat_id: getLocalStorageItem('seat_id'),
            desc: [],
            isShowDialog1: false,
            detailData: { specs_price: '' },
            packing_fee: '',
            notes: [],
            parameter: { sale_price: [] },
            shoppingCar: [],
            isShowDialog: false,
            isShowDialog1: false,
            secondMenuList: [],
            kiosk_menu_list: [],
            pid: "",
            cid: '',
            num: 1,
            menu_cateList: [],
            restaurants: [],
            state: '',
            buyStatusList: [{
                code: 2,
                name: '已购买'
            }, {
                code: 4,
                name: '待支付'
            }],
            constUrl,
            isUpdateDialog: false,
            updateCurrentRow: {},
            tableList: [],
            currentRow: {},
            form: {
                page: 1,
                pageSize: 15,
            },
            subloading: false
        }
    },
    computed: {
        total: function () {
            return (this.shoppingCar.reduce((total, item) => total + (item.price * item.num), 0) );
        }
    },
    methods: {
        addDesc(item) {
            const index = this.desc.indexOf(item);
            if (index === -1) {
                // 如果没有找到，添加到 notes 中
                this.desc.push(item);
            } else {
                // 如果已经存在，移除 notes 中的该项
                this.desc.splice(index, 1);
            }
            this.$forceUpdate()
        },
        async changeDesc() {
            let { data } = await remarks_list()
            this.desc = []
            this.remarkList = data
            this.$nextTick(() => {
                this.isShowDialog1 = true
            })
        },
        // 提交订单
        async submitOrder() {
if(this.shoppingCar.length==0){
    this.$message({
        type: 'waring',
        message: '请选择菜单!'
    });
    return
}
            let form = {
                seat_id: this.seat_id,
                packing_fee: this.packing_fee,
                desc: this.desc,
                order_detail: JSON.stringify(this.shoppingCar)
            }
            await create_order(form)
            this.prontDialogContent1()
            this.$router.push('/orderList')
        },
// 打印订单单
        prontDialogContent1() {
            const LODOP = getLodop();
            if (LODOP) {
                // 初始化打印任务
                LODOP.PRINT_INIT("打印任务");

                // 设置打印的页宽度及动态内容长度
                LODOP.SET_PRINT_PAGESIZE(3, 880, 0, ""); // 宽度138.5mm, 高度自适应

                // 打印头部信息
                LODOP.ADD_PRINT_TEXT(15, 50, 450, 25, "拐角老火锅");
                LODOP.SET_PRINT_STYLEA(1, "FontName", "汉仪旗黑-简");
                LODOP.SET_PRINT_STYLEA(1, "FontSize", 22);
                LODOP.SET_PRINT_STYLEA(1, "FontColor", 0);

                // 在标题下面添加横线
                LODOP.ADD_PRINT_LINE(60, 30, 60, 250, 0, 2); // 从 X=30 到 X=25 位置绘制线条，Y 坐标为 60，线宽 2 像素

                // 表头
                let startY = 80; // 起始Y坐标
                LODOP.ADD_PRINT_TEXT(90, 10, 431, 25, "菜品    数量    价格   总价");
                LODOP.SET_PRINT_STYLEA(3, "FontName", "Courier New");
                LODOP.SET_PRINT_STYLEA(3, "FontSize", 12);
                LODOP.SET_PRINT_STYLEA(3, "Bold", 1);

                // 遍历数据并打印每一行

                this.shoppingCar.forEach((item, index) => {
                    startY += 20; // 每项的高度间隔
                    const itemName = (item.name || "").padEnd(8, ' ');
                    const itemNum = String(item.num).padEnd(8, ' ');
                    const itemPrice = `￥${String(item.price || 0).padEnd(8, ' ')}`;
                    const itemTotal = `￥${String((item.num * item.price).toFixed(2) || 0).padEnd(4, ' ')}`;



                    startY += 20; // 调整备注的打印位置
                    LODOP.ADD_PRINT_TEXT(startY, 10, 431, 25, `${itemName} ${itemNum} ${itemPrice} ${itemTotal}`);
                    LODOP.SET_PRINT_STYLEA(3 + index+1 , "FontName", "Courier New");
                    LODOP.SET_PRINT_STYLEA(3 + index+1 , "FontSize", 8);
                    // LODOP.SET_PRINT_STYLEA(3 + index+1, "Bold", 1);
               if(item.notes!==''){
                   startY += 20; // 调整备注的打印位置
                   LODOP.ADD_PRINT_TEXT(startY, 30, 431, 20, `${item.notes}`);
                   LODOP.SET_PRINT_STYLEA(3 + index+2 , "FontName", "Courier New");
                   LODOP.SET_PRINT_STYLEA(3 + index+2 , "FontSize", 8);
               }else {
                   startY += 0; // 调整备注的打印位置
                   LODOP.ADD_PRINT_TEXT(0, 30, 431, 20, '');
                   LODOP.SET_PRINT_STYLEA(3 + index+2 , "FontName", "Courier New");
                   LODOP.SET_PRINT_STYLEA(3 + index+2 , "FontSize", 8);
               }

                });


                // // 在总价前面添加横线
                // startY += 40; // 给横线留点空间
                // LODOP.ADD_PRINT_LINE(startY, 30, startY, 250, 0, 2); // 从 X=30 到 X=25 位置绘制线条，Y 坐标为 60，线宽 2 像素

                // 增加空白区域
                startY += 50; // 给总价和底部留出额外的50px空间
                LODOP.ADD_PRINT_TEXT(startY, 50, 431, 25, " "); // 添加空白区域

                // 打印预览或直接打印
                // LODOP.PREVIEW(); // 预览
                LODOP.PRINT(); // 直接打印
            } else {
                alert("未能获取打印控件");
            }
        }
        ,
        // 清空购物车
        clearData() {
            this.$confirm('是否清除当前点餐数据', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.shoppingCar = [],
                    this.$message({
                        type: 'success',
                        message: '清除成功!'
                    });
            }).catch(() => {

            });
        },
        submitData() {
            this.subloading = true;
            let notes = this.notes.join('/')

            // 验证数据
            if ( !this.detailData.specs_price) {
                this.$message({
                    type: 'error',
                    message: '请选择价格与规格'
                })
                this.subloading = false
                return;
            }
            this.detailData = {
                price: this.detailData.price,
                specs_price: this.detailData.specs_price,
                notes: notes,
                name: this.parameter.name,
                num: 1,
                menu_id: this.parameter.id,
            }

            this.shoppingCar.push(this.detailData)
            this.isShowDialog = false;
            this.subloading = false
        },
        addNote(child, list) {
            if (list.some(item => this.notes.includes(item))) {
                const index = list.filter(item => this.notes.includes(item))
                this.notes = this.notes.filter(item => !index.includes(item));
                this.notes.splice(index, 1);
            }

            list.indexOf(child)
            const index = this.notes.indexOf(child);
            if (index === -1) {
                // 如果没有找到，添加到 notes 中
                this.notes.push(child);
            } else {
                // 如果已经存在，移除 notes 中的该项
                this.notes.splice(index, 1);
            }
        },
        changeParameter(item) {
            this.parameter = JSON.parse(JSON.stringify(item))
            this.notes = []
            this.detailData = []
            this.$nextTick(() => {
                this.isShowDialog = true

            })
        },
        chanFirstMenu(id, list) {
            this.pid = id
            this.secondMenuList = list
            this.cid = list[0].id
            if(id=='tg001'){
                this.queryTGList()
                return
            }
            this.queryKiosk_menu_list()
        },
        //获取团够套餐
        async queryTGList() {
            let { data } = await setmealList()
            data.map(x => {
                x.sale_price = Object.entries(x.sale_price).map(([size, price]) => ({
                    size,
                    price
                }));
                x.specs = Object.entries(x.specs).map(([title, price]) => ({
                    title,
                    price
                }));
                x.specs.map(y => {
                    y.price = y.price.split(',')

                })

                // const priceArray = valuesString.split(',');

            })
            this.kiosk_menu_list = data || []


        },
        async queryKiosk_menu_list() {
            let { data } = await menu_list({
                pid: this.pid, cid: this.cid
            })

            data.menuList.map(x => {
                x.sale_price = Object.entries(x.sale_price).map(([size, price]) => ({
                    size,
                    price
                }));
                x.specs = Object.entries(x.specs).map(([title, price]) => ({
                    title,
                    price
                }));
                x.specs.map(y => {
                    y.price = y.price.split(',')

                })

                // const priceArray = valuesString.split(',');

            })
            this.kiosk_menu_list = data.menuList || []
            this.packing_fee = data.packing_fee


        },
        async queryMenu_cateList() {
            let { data } = await menu_cateList()

            this.menu_cateList = data || []
            this.menu_cateList.push({
                title: '团购套餐',
                id: 'tg001',
                child: [{
                    title: '全部套餐',
                    id: 'tg001_01',
                }]
            })
            this.packing_fee = data.packing_fee
            this.pid = data[0].id
            this.secondMenuList = data[0].child
            this.cid = data[0].child[0].id
            this.queryKiosk_menu_list()

        },
        decrease(num, index) {
            if (this.shoppingCar[index].num >= 1) {
                if (this.shoppingCar[index].num == 1) {
                    this.shoppingCar.splice(index)
                } else {
                    this.shoppingCar[index].num--;
                }
                this.handleChange(this.shoppingCar[index].num);
                this.$forceUpdate()
            }
        },
        increase(num, index) {
            if (this.shoppingCar[index].num < 10000) {
                this.shoppingCar[index].num++;
                this.handleChange(this.shoppingCar[index].num);
                this.$forceUpdate()
            }
        },
        handleChange(value) {
        },

        //修改价格
        handleUpdate(row) {
            this.currentRow = {}
            let data = JSON.parse(JSON.stringify(row))
            this.updateCurrentRow = data
            this.isUpdateDialog = true
        },
        //详情
        handleStatus(row) {
            this.currentRow = {}
            let data = JSON.parse(JSON.stringify(row))
            this.currentRow = data
            this.isShowDialog = true
        },
        //更新价格
        async updatePrice(id) {
            let res = await martUpdatePrice({
                id: this.updateCurrentRow.id,
                price: this.updateCurrentRow.priceNow
            })
            if (res.code == 200);
            this.$notify({
                type: 'success',
                title: '提示',
                message: '改价成功！'
            })
            this.isUpdateDialog = false
            this.queryList()
        },


        // 分页大小改变
        handleSizeChange(val) {
            this.form.pageSize = val
            this.queryList()
        },
        // 当前页码改变
        handleCurrentChange(val) {
            this.form.page = val
            this.queryList()
        },
    }
    ,
    mounted() {
        this.queryMenu_cateList()
    }
}
</script>

<style lang="less" scoped>
.home {
    background: rgb(220, 220, 220);
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: flex-start;

    .shoppingCar {
        width: 260px;
        height: calc(100vh - 165px);
        overflow: hidden;
        background: white;
        box-sizing: border-box;
        padding-bottom: 120px;

        .topTiele {
            height: 60px;
            border-bottom: 1px rgb(220, 220, 220) solid;
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 0 10px;
            padding-right: 15px;
        }
    }
}

.menu-item {


    padding: 20px 15px;
    background-color: #fff;
    border-radius: 5px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.1);
    margin-bottom: 10px;
    font-family: Arial, sans-serif;

    .item-name {
        font-size: 16px;
        font-weight: 600;
        color: #333;
        margin: 0;
    }

    .item-desc {
        font-size: 12px;
        color: #999;
        margin: 5px 0 0 0;
    }

    .item-price-counter {
        display: flex;
        align-items: center;
        margin-top: 10px;
        justify-content: space-between;
    }

    .item-price {
        font-size: 18px;
        font-weight: 600;
        color: #FF6600;
        margin-right: 15px;
    }

    .item-counter {
        display: flex;
        align-items: center;
    }

    .counter-btn {
        width: 30px;
        height: 30px;
        border: 2px solid #FF6600;
        background-color: #fff;
        color: #FF6600;
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 18px;
        cursor: pointer;
        outline: none;
    }

    .item-quantity {
        margin: 0 10px;
        font-size: 16px;
        color: #333;
    }
}


.custom-input-number {
    display: flex;
    align-items: center;
    margin-right: 10px;

    .custom-counter {
        display: flex;
        align-items: center;

        .counter-btn {
            width: 20px;
            height: 20px;

            border: 2px solid #FF6600;
            background-color: #fff;
            color: #FF6600;
            border-radius: 50%;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 18px;
            cursor: pointer;
            outline: none;
        }

        .counter-btn.plus {
            background-color: #FF6600;
            color: #fff;
        }

        .minus {
            span {
                position: relative;
                top: -2px;
                /* 元素向下移动 10px */
                font-size: 26px;
            }
        }

        .item-quantity {
            margin: 0 10px;
            font-size: 16px;
            color: #333;
        }
    }
}

.menuListBox {
    height: 80vh;
    overflow: auto;
    box-sizing: border-box;
    padding-bottom: 20px;
}

.settlement {
    height: 70px;
    margin-top: 10px;
    width: 260px;
    background: white;
    box-sizing: border-box;
    padding: 10px;
    overflow: auto;

    .settlementBox {
        display: flex;
        justify-content: space-between;

        .settlementLeft {
            width: 60%;
        }

        .el-button {
            background: #FF6600;
            color: white;
            border-radius: 50px;
            padding: 0px 30px;
            height: 40px;
            font-size: 16px;
        }
    }

    h5 {
        font-size: 12px;
    }

    .settlementTips {
        span {
            font-size: 12px;
            margin-left: 5px;
            color: #7b7b7b;
        }
    }

    .settlement_price {
        margin: 5px 0;

        span {
            font-size: 12px
        }
    }
}

.main_MenuList {
    width: calc(100vw - 195px);
    margin-left: 10px;
    height: calc(100vh - 83px);
    overflow: auto;

    .firstMenu {
        text-align: center;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        font-weight: 600;
        transition: 0.3s all;

        p {
            cursor: pointer;
            margin-right: 15px;
            width: 160px;
            height: 30px;
            line-height: 15px;
            align-items: center;
            background: white;
            box-sizing: border-box;
            padding: 8px 0;
            transition: all 0.3s;
        }

        .pON {
            background: #FF6600;
            color: white;
        }
    }

    .secondMenu {
        text-align: center;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        flex-wrap: wrap;
        font-weight: 600;
        margin-top: 10px;

        p {
            cursor: pointer;
            margin-right: 10px;
            width: 140px;
            height: 30px;
            line-height: 15px;
            align-items: center;
            background: white;
            box-sizing: border-box;
            padding: 8px 0;
            transition: all 0.3s;
            margin-bottom: 10px;
        }

        .pON {
            background: #FF6600;
            color: white;
        }
    }

    .zxf_menu_list {
        display: flex;
        flex-wrap: wrap;
        margin-top: 10px;
    }
}

.parameterBox {
    h3 {
        font-size: 16px;
        font-weight: 600;
    }

    div {
        display: flex;
        align-items: center;
        justify-content: flex-start;
        height: 80px;
        line-height: 1;

        .divOn {
            color: #fff;
            background-color: #FF6600;
        }
    }

}


.parameterBox1 {
    h3 {
        font-size: 16px;
        font-weight: 600;
    }

    div {
        display: flex;
        align-items: center;
        justify-content: flex-start;
        height: 80px;
        line-height: 1;

        .divOn {
            color: #fff;
            background-color: #FF6600;
        }
    }

}

.descBox {
    h3 {
        margin-bottom: 15px;
    }

    div {
        display: flex;

        div {
            margin-right: 15px;
            font-size: 12px;
            border: 1px solid #2b2b2c;
            width: 80px;
            height: 25px;
            line-height: 25px;
            box-sizing: border-box;
            padding: 0 5px;
            border-radius: 20px;
            cursor: pointer;
            text-align: center;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .divOn {
            border-color: #FF6600;
            ;
            color: #FF6600;
        }
    }

}
</style>
